<template>
  <div v-loading="pageLoading">
    <!-- 卡片表頭 -->
    <el-card class="box-card" v-show="!pageLoading">
      <template #header>
        <div class="card-header">
          <span style="font-size: medium">{{ $t('user.info') }}</span>
        </div>
      </template>
      <el-form
        ref="staffRef"
        :model="staffForm"
        :rules="staffRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        :disabled="type == 'look'"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('user.account')" prop="userName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="staffForm.userName"
                :placeholder="$t('common.inputText') + $t('user.account')"
                :disabled="!changUserName"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('login.password')"
              prop="password"
              autocomplete="off"
              :show-password="true"
              class="requireLabel"
              v-if="isEdit"
            >
              <el-input
                class="required_input"
                v-model="staffForm.password"
                :placeholder="$t('login.passwordPlaceholder')"
                type="password"
                autocomplete="off"
                :show-password="true"
                maxlength="32"
                :minlength="pwLength"
              />
            </el-form-item>
            <el-form-item :label="$t('user.type')" class="requireLabel" prop="userType">
              <el-radio-group v-model="staffForm.userType" class="required_input">
                <el-radio :label="0">{{ $t('user.type0') }}</el-radio>
                <el-radio :label="1">{{ $t('user.type1') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('common.status')" class="requireLabel" prop="status">
              <el-select
                v-model="staffForm.status"
                class="m-2"
                :placeholder="$t('common.inputText') + $t('common.status')"
                size="default"
                style="margin: 0; position: relative; left: 10px"
                :disabled="statusDisabled"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('user.code')" class="requireLabel" prop="userCode">
              <el-input
                class="required_input"
                v-model="staffForm.userCode"
                :placeholder="$t('common.inputText') + $t('user.code')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('user.name')" prop="name" class="requireLabel">
              <el-input
                class="required_input"
                v-model="staffForm.name"
                :placeholder="$t('common.inputText') + $t('user.name')"
                :minlength="2"
                maxlength="50"
                show-word-limit
                @blur="genPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.enName')" prop="enName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="staffForm.enName"
                :placeholder="$t('common.inputText') + $t('common.enName')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('user.gender')" prop="gender" class="requireLabel">
              <el-radio-group v-model="staffForm.gender" class="required_input">
                <el-radio :label="1">{{ $t('user.male') }}</el-radio>
                <el-radio :label="0">{{ $t('user.female') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('user.entryDate')" prop="entryDate" class="requireLabel">
              <el-date-picker
                style="position: relative; left: 10px"
                v-model="staffForm.entryDate"
                :disabled-date="disabledDate"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="date"
                :placeholder="$t('common.selectText') + $t('user.entryDate')"
              />
            </el-form-item>
            <el-form-item :label="$t('user.joinGroups')" class="requireLabel" prop="groupIds">
              <el-select-v2
                v-model="staffForm.groupIds"
                multiple
                style="position: relative; left: 10px; width: 100%; font-size: 12px"
                :options="groupList"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('user.mobile')" class="normal_label" prop="mobileNo">
              <el-input
                v-model="staffForm.mobileNo"
                :placeholder="$t('common.inputText') + $t('user.mobile')"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="Email" prop="email" class="normal_label">
              <el-input
                v-model="staffForm.email"
                :placeholder="$t('common.inputText') + 'Email'"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('user.address')" class="normal_label">
              <el-input
                v-model="staffForm.address"
                :placeholder="$t('common.inputText') + $t('user.address')"
                type="textarea"
                :autosize="{ minRows: 2 }"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('user.passport')" prop="passportNo" class="normal_label">
              <el-input
                v-model="staffForm.passportNo"
                :placeholder="$t('common.inputText') + $t('user.passport')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('user.defaultLang')" class="normal_label">
              <el-select
                v-model="staffForm.language"
                class="m-2"
                :placeholder="$t('common.selectText') + $t('user.defaultLang')"
                size="default"
                style="margin: 0"
              >
                <el-option
                  v-for="item in languageOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('common.remark')" prop="remark" class="normal_label">
              <el-input
                v-model="staffForm.remark"
                :placeholder="$t('common.inputText') + $t('common.remark')"
                type="textarea"
                :autosize="{ minRows: 2 }"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('user.isLock')"
              prop="isLock"
              class="normal_label"
              v-if="staffForm.userId.length > 0"
            >
              <el-radio-group v-model="staffForm.isLock">
                <el-radio :label="1">{{ $t('common.yes') }}</el-radio>
                <el-radio :label="0">{{ $t('common.no') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('user.lockTime')"
              prop="lockTime"
              class="normal_label"
              v-if="staffForm.userId.length > 0"
            >
              <el-input v-model="staffForm.lockTime" :disabled="true"
            /></el-form-item>
            <el-form-item
              :label="$t('user.loginFailTimes')"
              prop="loginFailTimes"
              class="normal_label"
              v-if="staffForm.userId.length > 0"
            >
              <el-input
                v-model="staffForm.loginFailTimes"
                :disabled="true"
                style="text-align: right"
            /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row class="detailFooter">
        <el-col v-if="type == 'look'">
          <el-button type="primary" @click="goBack" plain>{{ $t('common.back') }}</el-button>
        </el-col>
        <el-col v-else>
          <el-button type="primary" :loading="loading" @click="saveStaff" plain>{{
            $t('common.save')
          }}</el-button>
          <el-button type="info" @click="goBack" plain>{{ $t('common.giveUp') }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted, onActivated, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getMd5Password } from '@/utils'
import { registerUser, getUserById, updateUser } from '@/api/staff'
import { useEmitt } from '@/hooks/web/useEmitt'
import { getAllGroups } from '@/api/system/authority'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { getPinyin } from '@/api/common'
import { useCache } from '@/hooks/web/useCache'
import { getSettings, getPasswordStrength } from '@/api/company'
import { ElMessage } from 'element-plus'

export default {
  name: 'EditStaff',
  props: {},
  setup() {
    const staffRef = ref()
    const { t } = useI18n()
    const router = useRouter()
    const { emitter } = useEmitt()
    const pageLoading = ref(true)
    const { wsCache } = useCache()
    const localeStore = useLocaleStoreWithOut()
    //当前语言
    const curLang = localeStore.getCurrentLocale.lang

    const state = reactive({
      type: '',
      // 員工資料
      staffForm: {
        userId: '',
        userName: '',
        password: '',
        userType: 0,
        status: 'enable',
        userCode: '',
        mobileNo: '',
        email: '',
        address: '',
        name: '',
        enName: '',
        gender: 1,
        entryDate: '',
        passportNo: '',
        language: '',
        remark: '',
        tenantId: '',
        loginFailTimes: 0,
        isLock: 0,
        lockTime: null,
        groupIds: []
      },
      staffRules: {
        userName: {
          required: true,
          pattern:
            /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{2,50}$/,
          message: t('common.errPassportNo'),
          trigger: ['blur', 'change']
        },
        password: {
          required: true,
          pattern:
            /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{3,32}$/,
          message: t('common.errPassportNo'),
          trigger: ['blur']
        },
        userType: {
          required: true,
          message: t('common.selectText') + t('user.type'),
          trigger: 'blur'
        },
        status: {
          required: true,
          message: t('common.selectText') + t('common.status'),
          trigger: 'blur'
        },
        groupIds: {
          required: true,
          message: t('user.joinGroups') + t('common.notEmpty'),
          trigger: ['blur', 'change']
        },
        userCode: { required: true, message: t('user.userCode'), trigger: ['blur', 'change'] },
        mobileNo: [
          {
            pattern: /^(\(){0,1}(\+){0,1}[\d\-( )]+$/,
            message: t('company.errMobileOrTelNo'),
            trigger: ['blur', 'change']
          },
          {
            pattern: '[^ \x22]+',
            message: t('company.emptyMsg'),
            trigger: ['blur', 'change']
          }
        ],
        email: {
          pattern: /^[^@]+[@]{1}[^@]+$/,
          message: 'Email' + t('company.errFormat'),
          trigger: 'blur'
        },
        name: [
          {
            required: true,
            message: t('user.name') + t('common.notEmpty'),
            trigger: ['blur', 'change']
          }
        ],
        gender: {
          required: true,
          message: t('user.gender') + t('common.notEmpty'),
          trigger: 'blur'
        },
        entryDate: { required: true, message: t('user.errEntryDateEmpty'), trigger: 'blur' },
        passportNo: {
          pattern:
            /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、 ]+$/,
          message: t('common.errPassportNo'),
          trigger: ['blur', 'change']
        }
      },
      // 賬戶類型類型options
      typeOptions: [
        {
          value: 0,
          label: t('user.type0')
        },
        {
          value: 1,
          label: t('user.type1')
        }
      ],
      // 客戶狀態options
      statusOptions: [
        {
          value: 'enable',
          label: t('user.enable')
        },
        {
          value: 'disable',
          label: t('user.disable')
        }
      ],
      // 預設界面語言options
      languageOptions: [
        {
          value: 'zh_HK',
          label: t('common.zhHk')
        },
        {
          value: 'zh_CN',
          label: t('common.zhCN')
        },
        {
          value: 'en',
          label: t('common.en')
        }
      ],
      statusDisabled: true,
      loading: false,
      // 隱藏密碼輸入
      isEdit: true,
      pwLength: 6,
      pwStrength: 3,
      changUserName: true, //修改用户名
      // 角色list
      groupList: []
    })
    onMounted(async () => {
      //获取用户组
      await getAllGroups().then((res) => {
        if (res) {
          var data = res.data as any
          var newData = []
          for (const row of data) {
            let name = row.groupName
            if (curLang == 'en') {
              name = row.enName
            } else if (curLang == 'zh_HK') {
              name = row.hkName
            }
            const newRow = { label: name, value: row.groupId }
            newData.push(newRow)
          }
          state.groupList = newData
        }
      })
      //获取租户配置
      const setting = await getSettings()
      state.staffForm.language = setting.defaultLang
      state.pwLength = setting.pwLength
      state.pwStrength = setting.pwStrength
      //初始化
      init()
    })
    const disabledDate = (time: Date) => {
      return time.getTime() > Date.now()
    }
    onActivated(async () => {})
    const methods = {
      // 保存员工
      saveStaff() {
        staffRef.value.validate(async (vaild) => {
          let form = Object.assign({}, state.staffForm)
          if (vaild) {
            state.loading = true
            if (form.userId) {
              // 修改
              await updateUser(form).then((res) => {
                if (res) {
                  emitter.emit('refreshStaffList')
                  methods.goBack()
                } else state.loading = false
              })
            } else {
              // 新增
              let strength = getPasswordStrength(state.staffForm.password)
              if (strength < state.pwStrength) {
                ElMessage.warning(t('settings.strengthCheck'))
                return
              }
              form.password = getMd5Password(form.password)
              await registerUser(form)
                .then((res) => {
                  if (res) {
                    emitter.emit('refreshStaffList')
                    methods.goBack()
                  } else state.loading = false
                })
                .catch(() => {
                  state.loading = false
                })
            }
          }
        })
      },
      async genPinyin(event) {
        const text = event.target.value
        if (!text || text.length == 0) {
          return
        }
        if (state.staffForm.enName.length > 0) {
          return
        }
        let data = (await getPinyin(text, 50)) as any
        state.staffForm.enName = data.data
      },
      // 返回
      goBack() {
        emitter.emit('closeTag', {
          closePath: router.currentRoute.value.fullPath,
          backPath: '/Staff/StaffData'
        })
      }
    }
    //渲染页面的接口
    const init = async () => {
      //修改
      state.type = wsCache.get('staffStatus')
      if (state.type == 'update' || state.type == 'look') {
        state.statusDisabled = false
        state.isEdit = false
        const res = await getUserById(wsCache.get('staffId'))
        state.staffForm = res.data
        state.changUserName = state.staffForm.userName.indexOf('-') > 0
      }
      setTimeout(() => {
        pageLoading.value = false
      }, 1000)
    }
    return {
      ...toRefs(state),
      staffRef,
      ...methods,
      disabledDate,
      pageLoading,
      curLang
    }
  }
}
</script>
<style lang="less" scoped>
.box-card {
  padding-left: 50px;
  padding-right: 50px;
}
:deep(.el-form) {
  padding-top: 10px;
}
:deep(.el-input) {
  font-size: 12px;
}
:deep(.el-textarea__inner) {
  height: 80px;
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}

.normal_label,
.required_input {
  position: relative;
  left: 10px;
}
:deep(.normal_label .el-form-item__error) {
  left: 0px;
}
:deep(.requireLabel .el-form-item__error) {
  margin-left: 10px;
}
// 查詢狀態下一般input輸入框已填信息變黑色展示
:deep(.el-input.is-disabled .el-input__inner) {
  color: #000000;
}
// 查詢狀態下textarea輸入框已填信息變黑色展示
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #000000;
}

// 查詢狀態下一般input輸入框placeholder隱藏
:deep(.el-input.is-disabled .el-input__inner) {
  &::placeholder {
    color: transparent;
  }
}
// 查詢狀態下textarea輸入框placeholder隱藏
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  &::placeholder {
    color: transparent;
  }
}
</style>
